import pymysql
from pymysql.cursors import DictCursor
from threading import Lock
from src.env import ENV


class Database:
    _instance = None
    _connection = None
    _lock = Lock()

    def __new__(cls, host, user, password, db):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
                    try:
                        cls._connection = pymysql.connect(
                            host=host,
                            user=user,
                            password=password,
                            db=db,
                            cursorclass=DictCursor
                        )
                    except pymysql.MySQLError as e:
                        print(f"Error connecting to MySQL: {e}")
                        cls._instance = None
                        cls._connection = None
        return cls._instance

    @property
    def connection(self):
        return self._connection

    def close_connection(self):
        if self._connection:
            self._connection.close()
            self._connection = None
            self._instance = None


LOCAL_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': 'root',
    'db': 'test'
}

TEST_CONFIG = {
    'host': 'localhost',
    'user': 'your_user',
    'password': 'your_password',
    'db': 'your_db'
}

if ENV == 'test':
    db = Database(**TEST_CONFIG)
else:
    db = Database(**LOCAL_CONFIG)
